from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Friendships, User
import uuid
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import to_beijing_time

bp = Blueprint('friendships', __name__, url_prefix='/friendships/')

class AddFriend(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        friend_id = data.get('friend_id')
        current_user = get_jwt_identity()
        
        if not friend_id:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        # 检查是否已经是好友
        existing_friendship = Friendships.query.filter(
            ((Friendships.user_id1 == user.id) & (Friendships.user_id2 == friend_id)) |
            ((Friendships.user_id1 == friend_id) & (Friendships.user_id2 == user.id))
        ).first()
        
        if existing_friendship:
            return HResult().get_result('error', '已经是好友关系!')
            
        friendship = Friendships(
            id=str(uuid.uuid4()),
            user_id1=user.id,
            user_id2=friend_id,
            created_time=to_beijing_time(datetime.utcnow())
        )
            
        db.session.add(friendship)
        db.session.commit()
        return HResult().get_result('success', '添加好友成功!')

class DeleteFriend(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        friend_id = data.get('friend_id')
        current_user = get_jwt_identity()
        
        if not friend_id:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        friendship = Friendships.query.filter(
            ((Friendships.user_id1 == user.id) & (Friendships.user_id2 == friend_id)) |
            ((Friendships.user_id1 == friend_id) & (Friendships.user_id2 == user.id))
        ).first()
        
        if friendship:
            db.session.delete(friendship)
            db.session.commit()
            return HResult().get_result('success', '删除好友成功!')
        else:
            return HResult().get_result('error', '好友关系不存在!')

class QueryUserFriends(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()
        
        # 获取所有好友关系
        friendships = Friendships.query.filter(
            (Friendships.user_id1 == user.id) | (Friendships.user_id2 == user.id)
        ).all()
        
        friends_data = []
        for friendship in friendships:
            friend = friendship.user_ if friendship.user_id1 == user.id else friendship.user
            friend_data = friend.to_dict()
            friend_data['friendship_id'] = friendship.id
            friend_data['created_time'] = friendship.created_time.strftime('%Y-%m-%d %H:%M:%S')
            friends_data.append(friend_data)
            
        return HResult().get_result('success', data=friends_data)

api = Api(bp)
api.add_resource(AddFriend, '/add/', endpoint='add')
api.add_resource(DeleteFriend, '/delete/', endpoint='delete')
api.add_resource(QueryUserFriends, '/list/', endpoint='list') 